package com.carrental.vehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.vehicle.dto.VehicleDTO;
import com.carrental.vehicle.entity.Store;
import com.carrental.vehicle.entity.Vehicle;
import com.carrental.vehicle.entity.VehicleBrand;
import com.carrental.vehicle.entity.VehicleSeries;
import com.carrental.vehicle.enums.VehicleStatusEnum;
import com.carrental.vehicle.mapper.StoreMapper;
import com.carrental.vehicle.mapper.VehicleBrandMapper;
import com.carrental.vehicle.mapper.VehicleMapper;
import com.carrental.vehicle.mapper.VehicleSeriesMapper;
import com.carrental.vehicle.service.VehicleService;
import com.carrental.vehicle.vo.VehicleVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 车辆服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    private final VehicleBrandMapper vehicleBrandMapper;
    private final VehicleSeriesMapper vehicleSeriesMapper;
    private final StoreMapper storeMapper;

    /**
     * 根据ID获取车辆详情
     *
     * @param id 车辆ID
     * @return 车辆详情
     */
    @Override
    public VehicleVO getVehicleById(Long id) {
        // 查询车辆信息
        Vehicle vehicle = getById(id);
        if (vehicle == null) {
            throw new BusinessException("车辆不存在");
        }
        
        return convertToVO(vehicle);
    }

    /**
     * 保存或更新车辆信息
     *
     * @param vehicleDTO 车辆信息DTO
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateVehicle(VehicleDTO vehicleDTO) {
        // 检查品牌是否存在
        VehicleBrand brand = vehicleBrandMapper.selectById(vehicleDTO.getBrandId());
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        
        // 检查系列是否存在
        VehicleSeries series = vehicleSeriesMapper.selectById(vehicleDTO.getSeriesId());
        if (series == null) {
            throw new BusinessException("系列不存在");
        }
        
        // 检查系列是否属于该品牌
        if (!Objects.equals(series.getBrandId(), vehicleDTO.getBrandId())) {
            throw new BusinessException("系列不属于该品牌");
        }
        
        // 检查门店是否存在
        Store store = storeMapper.selectById(vehicleDTO.getStoreId());
        if (store == null) {
            throw new BusinessException("门店不存在");
        }
        
        // 检查车牌号是否重复
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getLicensePlate, vehicleDTO.getLicensePlate())
                .eq(Vehicle::getDeleted, 0);
        if (vehicleDTO.getId() != null) {
            queryWrapper.ne(Vehicle::getId, vehicleDTO.getId());
        }
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("车牌号已存在");
        }
        
        // 封装车辆信息
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleDTO, vehicle);
        
        LocalDateTime now = LocalDateTime.now();
        
        if (vehicleDTO.getId() == null) {
            // 新增
            vehicle.setStatus(1); // 默认可用状态
            vehicle.setCreateTime(now);
            vehicle.setUpdateTime(now);
            vehicle.setDeleted(0);
            return save(vehicle);
        } else {
            // 更新
            vehicle.setUpdateTime(now);
            return updateById(vehicle);
        }
    }

    /**
     * 根据ID删除车辆
     *
     * @param id 车辆ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteVehicleById(Long id) {
        Vehicle vehicle = getById(id);
        if (vehicle == null) {
            throw new BusinessException("车辆不存在");
        }
        
        // 检查车辆状态，已租状态不能删除
        if (vehicle.getStatus() == 2) {
            throw new BusinessException("车辆处于已租状态，不能删除");
        }
        
        return removeById(id);
    }

    /**
     * 分页查询车辆
     *
     * @param page    分页参数
     * @param vehicle 查询条件
     * @return 分页结果
     */
    @Override
    public Page<VehicleVO> pageVehicle(Page<Vehicle> page, Vehicle vehicle) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据条件查询
        queryWrapper.eq(vehicle.getBrandId() != null, Vehicle::getBrandId, vehicle.getBrandId())
                .eq(vehicle.getSeriesId() != null, Vehicle::getSeriesId, vehicle.getSeriesId())
                .eq(vehicle.getType() != null, Vehicle::getType, vehicle.getType())
                .eq(vehicle.getStatus() != null, Vehicle::getStatus, vehicle.getStatus())
                .eq(vehicle.getStoreId() != null, Vehicle::getStoreId, vehicle.getStoreId())
                .like(vehicle.getName() != null, Vehicle::getName, vehicle.getName())
                .like(vehicle.getLicensePlate() != null, Vehicle::getLicensePlate, vehicle.getLicensePlate())
                .orderByDesc(Vehicle::getCreateTime);
        
        Page<Vehicle> vehiclePage = page(page, queryWrapper);
        
        // 转换VO
        Page<VehicleVO> vehicleVOPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<VehicleVO> vehicleVOList = new ArrayList<>();
        
        for (Vehicle v : vehiclePage.getRecords()) {
            vehicleVOList.add(convertToVO(v));
        }
        
        vehicleVOPage.setRecords(vehicleVOList);
        return vehicleVOPage;
    }

    /**
     * 根据车辆类型查询车辆列表
     *
     * @param type 车辆类型
     * @return 车辆列表
     */
    @Override
    public List<VehicleVO> listVehicleByType(Integer type) {
        List<Vehicle> vehicles = list(new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getType, type)
                .eq(Vehicle::getStatus, 1) // 只查询可用状态的车辆
                .eq(Vehicle::getDeleted, 0)
                .orderByDesc(Vehicle::getCreateTime));
        
        return convertToVOList(vehicles);
    }

    /**
     * 根据门店ID查询车辆列表
     *
     * @param storeId 门店ID
     * @return 车辆列表
     */
    @Override
    public List<VehicleVO> listVehicleByStore(Long storeId) {
        List<Vehicle> vehicles = list(new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getStoreId, storeId)
                .eq(Vehicle::getStatus, 1) // 只查询可用状态的车辆
                .eq(Vehicle::getDeleted, 0)
                .orderByDesc(Vehicle::getCreateTime));
        
        return convertToVOList(vehicles);
    }

    /**
     * 根据品牌ID查询车辆列表
     *
     * @param brandId 品牌ID
     * @return 车辆列表
     */
    @Override
    public List<VehicleVO> listVehicleByBrand(Long brandId) {
        List<Vehicle> vehicles = list(new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getBrandId, brandId)
                .eq(Vehicle::getStatus, 1) // 只查询可用状态的车辆
                .eq(Vehicle::getDeleted, 0)
                .orderByDesc(Vehicle::getCreateTime));
        
        return convertToVOList(vehicles);
    }

    /**
     * 更新车辆状态
     *
     * @param id     车辆ID
     * @param status 车辆状态
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVehicleStatus(Long id, Integer status) {
        // 检查状态值是否合法
        if (status < 1 || status > 4) {
            throw new BusinessException("状态值不合法");
        }
        
        Vehicle vehicle = getById(id);
        if (vehicle == null) {
            throw new BusinessException("车辆不存在");
        }
        
        vehicle.setStatus(status);
        vehicle.setUpdateTime(LocalDateTime.now());
        
        return updateById(vehicle);
    }

    /**
     * 将实体对象转换为VO对象
     *
     * @param vehicle 车辆实体
     * @return 车辆VO
     */
    private VehicleVO convertToVO(Vehicle vehicle) {
        VehicleVO vehicleVO = new VehicleVO();
        BeanUtils.copyProperties(vehicle, vehicleVO);
        
        // 查询品牌信息
        VehicleBrand brand = vehicleBrandMapper.selectById(vehicle.getBrandId());
        if (brand != null) {
            vehicleVO.setBrandName(brand.getName());
        }
        
        // 查询系列信息
        VehicleSeries series = vehicleSeriesMapper.selectById(vehicle.getSeriesId());
        if (series != null) {
            vehicleVO.setSeriesName(series.getName());
        }
        
        // 查询门店信息
        Store store = storeMapper.selectById(vehicle.getStoreId());
        if (store != null) {
            vehicleVO.setStoreName(store.getName());
            vehicleVO.setStoreProvince(store.getProvince());
            vehicleVO.setStoreCity(store.getCity());
            vehicleVO.setStoreDistrict(store.getDistrict());
            vehicleVO.setStoreAddress(store.getAddress());
        }
        
        // 设置车辆类型名称
        switch (vehicle.getType()) {
            case 1:
                vehicleVO.setTypeName("经济型");
                break;
            case 2:
                vehicleVO.setTypeName("舒适型");
                break;
            case 3:
                vehicleVO.setTypeName("豪华型");
                break;
            case 4:
                vehicleVO.setTypeName("SUV");
                break;
            case 5:
                vehicleVO.setTypeName("MPV");
                break;
            default:
                vehicleVO.setTypeName("未知");
        }
        
        // 设置变速箱类型名称
        switch (vehicle.getTransmissionType()) {
            case 1:
                vehicleVO.setTransmissionTypeName("手动");
                break;
            case 2:
                vehicleVO.setTransmissionTypeName("自动");
                break;
            default:
                vehicleVO.setTransmissionTypeName("未知");
        }
        
        // 设置燃油类型名称
        switch (vehicle.getFuelType()) {
            case 1:
                vehicleVO.setFuelTypeName("汽油");
                break;
            case 2:
                vehicleVO.setFuelTypeName("柴油");
                break;
            case 3:
                vehicleVO.setFuelTypeName("电动");
                break;
            case 4:
                vehicleVO.setFuelTypeName("混合动力");
                break;
            default:
                vehicleVO.setFuelTypeName("未知");
        }
        
        // 设置车辆状态名称
        switch (vehicle.getStatus()) {
            case 1:
                vehicleVO.setStatusName("可用");
                break;
            case 2:
                vehicleVO.setStatusName("已租");
                break;
            case 3:
                vehicleVO.setStatusName("维修中");
                break;
            case 4:
                vehicleVO.setStatusName("报废");
                break;
            default:
                vehicleVO.setStatusName("未知");
        }
        
        return vehicleVO;
    }

    /**
     * 将实体对象列表转换为VO对象列表
     *
     * @param vehicles 车辆实体列表
     * @return 车辆VO列表
     */
    private List<VehicleVO> convertToVOList(List<Vehicle> vehicles) {
        List<VehicleVO> vehicleVOList = new ArrayList<>();
        for (Vehicle vehicle : vehicles) {
            vehicleVOList.add(convertToVO(vehicle));
        }
        return vehicleVOList;
    }

    @Override
    public List<VehicleDTO> getPopularVehicles(Integer limit) {
        log.info("查询热门车辆，数量限制：{}", limit);
        
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getStatus, VehicleStatusEnum.AVAILABLE.getCode());
        queryWrapper.orderByDesc(Vehicle::getRentalCount);
        queryWrapper.last("LIMIT " + limit);
        
        List<Vehicle> vehicles = list(queryWrapper);
        
        return vehicles.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRentalCount(Long vehicleId) {
        log.info("更新车辆租赁次数，车辆ID：{}", vehicleId);
        
        Vehicle vehicle = getById(vehicleId);
        if (vehicle == null) {
            log.error("车辆不存在，ID：{}", vehicleId);
            return false;
        }
        
        // 如果租赁次数为空，设置为1，否则加1
        if (vehicle.getRentalCount() == null) {
            vehicle.setRentalCount(1);
        } else {
            vehicle.setRentalCount(vehicle.getRentalCount() + 1);
        }
        
        vehicle.setUpdateTime(LocalDateTime.now());
        
        return updateById(vehicle);
    }
    
    @Override
    public VehicleDTO getVehicleDetail(Long id) {
        log.info("获取车辆详情，ID：{}", id);
        
        Vehicle vehicle = getById(id);
        if (vehicle == null) {
            log.error("车辆不存在，ID：{}", id);
            throw new BusinessException("车辆不存在");
        }
        
        return convertToDTO(vehicle);
    }
    
    /**
     * 将Vehicle实体转换为VehicleDTO
     * @param vehicle 车辆实体
     * @return 车辆DTO
     */
    private VehicleDTO convertToDTO(Vehicle vehicle) {
        if (vehicle == null) {
            return null;
        }
        
        VehicleDTO dto = new VehicleDTO();
        BeanUtils.copyProperties(vehicle, dto);
        
        // 设置品牌名称
        if (vehicle.getBrandId() != null) {
            VehicleBrand vehicleBrand = vehicleBrandMapper.selectById(vehicle.getBrandId());
            if (vehicleBrand != null) {
                dto.setBrandName(vehicleBrand.getName());
                dto.setBrandLogo(vehicleBrand.getLogo());
            }
        }
        
        // 设置系列名称
        if (vehicle.getSeriesId() != null) {
            VehicleSeries vehicleSeries = vehicleSeriesMapper.selectById(vehicle.getSeriesId());
            if (vehicleSeries != null) {
                dto.setSeriesName(vehicleSeries.getName());
            }
        }
        
        return dto;
    }
} 